import json
import os


def merge_train_val(train_json, val_json, output_json):
    # 读取训练集标注
    with open(train_json, 'r') as f:
        train_data = json.load(f)

    # 读取验证集标注
    with open(val_json, 'r') as f:
        val_data = json.load(f)

    # 合并数据并重新分配标注ID
    merged_annotations = []
    current_id = 0
    for ann in train_data['annotations'] + val_data['annotations']:
        ann_copy = ann.copy()
        ann_copy['id'] = current_id
        merged_annotations.append(ann_copy)
        current_id += 1

    # 合并数据
    merged_data = {
        'info': train_data['info'],
        'licenses': train_data['licenses'],
        'categories': train_data['categories'],
        'images': train_data['images'] + val_data['images'],
        'annotations': merged_annotations
    }

    # 保存合并后的标注
    with open(output_json, 'w') as f:
        json.dump(merged_data, f)


if __name__ == '__main__':
    data_root = '/media/ross/8TB/project/lsh/dataset/microAlgea/microAlgaeOri/'
    merge_train_val(
        train_json=os.path.join(data_root, 'annotations/instances_train2017.json'),
        val_json=os.path.join(data_root, 'annotations/instances_val2017.json'),
        output_json=os.path.join(data_root, 'annotations/instances_trainval.json')
    )
